package request

import (
	"hsy/app/models"
	"hsy/util"
	"regexp"

	"github.com/go-playground/validator/v10"
)

var validate = validator.New()

// UserCreateRequest 创建用户类型
type UserCreateRequest struct {
	Name     string `json:"name" validate:"required"`
	Sex      int    `json:"set" validate:"oneof=0 1"` // 0 男  1 女
	Username string `json:"username" validate:"required,checkUsername"`
	Password string `json:"password" validate:"required,pswdComplex"`
}

// UserUpdateRequest 更新用户类型
type UserUpdateRequest struct {
	ID       int    `json:"id" validate:"required"`
	Name     string `json:"name" validate:"required"`
	Sex      int    `json:"set" validate:"oneof=0 1"` // 0 男  1 女
	Username string `json:"username" validate:"required"`
	Password string `json:"password"`
}

// LoginRequest 登录类型
type LoginRequest struct {
	Username string `json:"username" validate:"required"`
	Password string `json:"password" validate:"required"`
}

func validateMsgs() map[string]string {
	msg := util.ValidateMessages{}
	msg["Name.required"] = "name为必填字段"
	msg["Sex.oneof"] = "sex字段必须是0,1中一个"
	msg["Username.required"] = "username为必填字段"
	msg["Username.checkUsername"] = "username不能重复"
	msg["Password.required"] = "password为必填字段"
	msg["password.pswdComplex"] = "密码长度为8-16位，包括字母数字"
	return msg
}

func pswdComplex(fl validator.FieldLevel) bool {
	var numPattern = "^\\d+$"
	var pattern = "[a-zA-Z0-9]{8,16}"
	val := fl.Field().String()
	match1, _ := regexp.MatchString(pattern, val)
	match2, _ := regexp.MatchString(numPattern, val)
	if match1 && !match2 {
		return true
	}
	return false
}

// 查询用户名是否存在
func checkUsername(fl validator.FieldLevel) bool {
	userModel := models.UserModel{}
	val := fl.Field().String()
	if userModel.CheckUsernameExist(val) {
		return false
	}
	return true
}

// ValidateCreate 新增表单验证
func (u *UserCreateRequest) ValidateCreate() (msg util.ValidateMessages, e error) {
	validate.RegisterValidation("checkUsername", checkUsername)
	validate.RegisterValidation("pswdComplex", pswdComplex)
	err := validate.Struct(u)
	return util.ValidatorMessage(err, validateMsgs())
}

// ValidateUpdate 更新表单验证
func (u *UserUpdateRequest) ValidateUpdate() (msg util.ValidateMessages, e error) {
	err := validate.Struct(u)
	return util.ValidatorMessage(err, validateMsgs())
}

// ValidateLogin 登录表单验证
func (u *LoginRequest) ValidateLogin() (msg util.ValidateMessages, e error) {
	err := validate.Struct(u)
	return util.ValidatorMessage(err, validateMsgs())
}
